package com.smart.manager.work.repository;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.member.entities.views.MemberPigView;
import com.smart.manager.product.entities.models.BasicCamera;
import com.smart.manager.work.entities.assembler.WorkOrder;
import com.smart.manager.work.entities.body.RPigOrder;
import com.smart.manager.work.entities.enums.PigOrderKind;
import com.smart.manager.work.entities.enums.PigOrderStatus;
import com.smart.manager.work.entities.models.PigOrder;
import com.smart.manager.work.entities.models.query.QPigOrder;
import com.smart.manager.work.views.BasicStaffView;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * 工单
 * @author leo
 * @date 2023/09/20
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class PigOrderRepository {

    private final TaskMainRepository taskMainRepository;

    public Page<PigOrder> pageList(RPigOrder.SearchBody search) {
        QPigOrder query = new QPigOrder();
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        Opt.ofBlankAble(search.getKind()).ifPresent(x -> query.kind.eq(x));
        Opt.ofBlankAble(search.getStaff()).ifPresent(x -> query.staff.code.eq(x));
        Opt.ofBlankAble(search.getStatus()).ifPresent(x -> query.status.eq(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigOrder>().load(query.findPagedList());
    }

    public void add(RPigOrder.EditBody body) {
        QPigOrder query = new QPigOrder();
        PigOrder record = query.code.eq(body.getCode()).setMaxRows(1).findOne();
        Assert.isNull(record, "创建失败:, 工单代码已存在");
        BeanUtil.copyProperties(body, PigOrder.class).save();
    }


    public void update(Long id, RPigOrder.EditBody body) {
        PigOrder record = getOneById(id);
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }


    /**
     * 系统创建工单
     * @param kind 分类
     * @param content 工单内容
     */
    public String createAWorkOrder(MemberPigView pig, BasicStaffView staffView, PigOrderKind kind, PigOrderStatus status, Object content) {
        String datetime = String.format("GD%s%s", DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN), RandomUtil.randomNumbers(3));
        long oderId  = IdUtil.getSnowflakeNextId();
        PigOrder pigOrder = new PigOrder().setPig(pig).setStaff(staffView).setCode(datetime).setStatus(status).setKind(kind).setContent(content);
        pigOrder.setId(oderId);
        pigOrder.insert();
        if (ObjUtil.equals(PigOrderKind.L1,kind)){
            //入栏工单需要客服来处理
            taskMainRepository.addKind(oderId);
        }
        return datetime;
    }


    /**
     * 工单分配管家
     * @param id 工单id
     * @param code 管家id
     */
    public void assign(Long id, String code) {
        PigOrder record = getOneById(id);
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        record.setStaff(new BasicStaffView().setCode(code)).setStatus(PigOrderStatus.PROGRESS);
        Objects.requireNonNull(record).update();
    }


    /**
     * 提交工单 入卷工单
     * @param id 工单id
     * @param body 入圈的body
     */
    @Transactional(rollbackFor = Exception.class)
    public void submit(Long id, RPigOrder.enterTheCircleBody body) {
        PigOrder record = getOneById(id);
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        Assert.isTrue(record.getStatus().equals(PigOrderStatus.ALLOCATED),"重复提交");
        record.setContent(BeanUtil.copyProperties(body, WorkOrder.class)).setStatus(PigOrderStatus.COMPLETED).setCompleteTime(LocalDateTime.now());
        Optional<MemberMaterialPig> orEmpty = new QMemberMaterialPig().id.eq(body.getId()).findOneOrEmpty();
        Assert.isFalse(orEmpty.isEmpty(),"未找到猪猪订单");
        BeanUtil.copyProperties(body,orEmpty.get());
        orEmpty.get().update();
    }


    /**
     * 根据id获取数据
     * @param id id
     * @return {@link BasicCamera}
     */
    private PigOrder getOneById(Long id) {
        QPigOrder query = new QPigOrder();
        PigOrder record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        return record;
    }


    public int delByIds(List<Long> ids) {
        List<PigOrder> list = new QPigOrder().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (PigOrder item : list) {
            log.warn("判断数据是否能被删除");
        }
        return DB.deleteAll(list);
    }

}






